package com.n9.util;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.DateDeserializers.DateDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.IOException;
import java.util.*;

/**
 * json工具类
 * @author ice
 * @Version 2017年10月27日
 */
public abstract class JsonUtils {
	private static final ObjectMapper mapper;
	
	static {
		SimpleModule simpleModule = new SimpleModule();  
        simpleModule.addDeserializer(Date.class, new DateDeserializer(){
			private static final long serialVersionUID = 1L;

			@Override
        	public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
				String text = jp.getText();
				if (text == null || text.length() == 0) {
					return null;
				}
				return new Date(Long.parseLong(text));
        	}
        });  
		mapper = new ObjectMapper();
		mapper.registerModule(simpleModule);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.setSerializationInclusion(Include.NON_NULL);
	}
	
	/**
	 * json转指定class
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> T json2Bean(Class<T> clazz, String json) {
		try {
			return mapper.readValue(json, clazz);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
	
	/**
	 * json转map
	 * @param json
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<Object, Object> json2Map(String json) {
		return json2Bean(Map.class, json);
	}
	
	/**
	 * javaBean转json
	 * @param object
	 * @return
	 */
	public static String bean2Json(Object object) {
		try {
			return mapper.writeValueAsString(object);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
	
	/**
	 * json转set
	 * @param fieldGenericType
	 * @param jsonData
	 * @return
	 */
	public static Set<Object> json2Set(Class<?> fieldGenericType, String jsonData) {
		JavaType jt = mapper.getTypeFactory().constructParametricType(HashSet.class, fieldGenericType);
		try {
			return mapper.readValue(jsonData, jt);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * json转list
	 * @param fieldGenericType
	 * @param jsonData
	 * @return
	 */
	public static <T> List<T> json2List(Class<T> fieldGenericType, String jsonData) {
		JavaType jt = mapper.getTypeFactory().constructParametricType(ArrayList.class, fieldGenericType);
		try {
			return mapper.readValue(jsonData, jt);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
